package com.wenjunwu.blog.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wenjunwu.blog.dao.SystemRoleDao;
import com.wenjunwu.blog.dao.SystemUserDao;
import com.wenjunwu.blog.em.OptionEnum;
import com.wenjunwu.blog.entity.SystemRole;
import com.wenjunwu.blog.entity.SystemUser;
import com.wenjunwu.blog.service.SystemUserService;

@Service
public class SystemUserServiceImpl implements SystemUserService {

	@Autowired
	private SystemUserDao systemUserDao;

	@Autowired
	private SystemRoleDao systemRoleDao;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public SystemUser findUser(Long id) {
		return systemUserDao.findUser(id);
	}

	@Override
	public List<SystemUser> findAllUsers() {
		return systemUserDao.findUsers();
	}

	@Override
	public Page<SystemUser> findUsersPage(int pageNum, int pageSize,Map<String, Object> params) {
		return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> systemUserDao.findUsersPage(params));
	}

	@Override
	public SystemUser findById(long id) {
		
		return null;
	}

	@Override
	public boolean isUserExist(SystemUser user) {
		return false;
	}

	@Override
	public boolean updateUser(SystemUser systemUser) {
		boolean optResult = false;
		if(systemUserDao.update(systemUser)>0) {
			optResult=true;
		}
		return optResult;
	}

	@Override
	public void save(SystemUser systemUser) {
		if (StringUtils.isEmpty(systemUser.getPassword())) {
			systemUser.setPassword("11111111");
		}
		Date currentDate = new Date();
		systemUser.setPassword(passwordEncoder.encode(systemUser.getPassword()));
		systemUser.setStatus(OptionEnum.OPTION_VALID.getValue());
		systemUser.setCreateTime(currentDate);
		systemUser.setUpdateTime(currentDate);
		systemUserDao.insert(systemUser);
		// 保存角色信息
		SystemRole record = new SystemRole();
		record.setRoleName("USER");
		record.setStatus(OptionEnum.OPTION_VALID.getValue());
		record.setUsername(systemUser.getUsername());
		systemRoleDao.insert(record);
	}

	@Override
	public boolean checkUser(String username) {
		SystemUser systemUser = systemUserDao.findUser(username);
		if (StringUtils.isEmpty(systemUser)) {
			return false;
		}
		return true;
	}
}
